package com.edu.model;


import java.util.HashMap;
import java.util.Map;


public class Board {

	//设置棋盘的行数和列数
	public final int BOARD_ROW = 9, BOARD_COL = 10;
	//每个格子的宽度
	//public final int d = 40;

	//棋子的集合
	private Map<String,Piece> pieces = new HashMap<>();
	//每个落子的位置数组
	private Piece[][] cells = new Piece[BOARD_ROW][BOARD_COL];
	//玩家颜色
	private char player = 'r' ;
	
	public Board(Map<String, Piece> pieces) {
		this.pieces = pieces;
		setCells(pieces);
	}
	//判断当前行列是否在棋盘上
	public boolean isInside(int row, int col) {
        return !(row < 0 || row >= BOARD_ROW
                || col < 0 || col >= BOARD_COL);
	}
	public boolean isInside(Position position) {
        return isInside(position.row, position.col);
	}
	//判断当前行列是否为空(无子)
	public boolean isEmpty(Position position) {
        return isEmpty(position.row, position.col);
    }
    public boolean isEmpty(int row, int col) {
        return isInside(row, col) && cells[row][col] == null;
    }
    
    //在棋盘中更新棋子位置
    public boolean update(Piece piece) {
        Position pos = piece.getPosition();
        cells[pos.row][pos.col] = piece;
        return true;
    }
    
    public Piece updatePiece(String key, Position newPos) {
        Piece orig = pieces.get(key);
        Piece inNewPos = getPiece(newPos);
        /* 如果新的插槽被另一个部件占用，那么它将被杀死.*/
        if (inNewPos != null)
            pieces.remove(inNewPos.getKey());
        /* 清除原始插槽并更新新插槽。*/
        Position origPos = orig.getPosition();
        cells[origPos.row][origPos.col] = null;
        cells[newPos.row][newPos.col] = orig;
        orig.setPosition(newPos);
        player = (player == 'r') ? 'b' : 'r';
        return inNewPos;
    }
    //撤销(暂不理解)
    public boolean backPiece(String key) {
    	Position origPos = pieces.get(key).getPosition();
        cells[origPos.row][origPos.col] = pieces.get(key);
        return true;
    }
    
    public Map<String, Piece> getPieces() {
		return pieces;
	}
	//获取当前位置的棋子，如果没有返回null
    public Piece getPiece(Position newPos) {
		return cells[newPos.row][newPos.col];
	}
	public Piece getPiece(int row, int col) {
        return cells[row][col];
	}
	private void setCells(Map<String, Piece> pieces) {
		for (Piece piece : pieces.values()) {  
			  Position pos = piece.getPosition();
			  this.cells[pos.row][pos.row] = piece;
		} 
	}
}
